import {
  COMMIT_TEACHER, DELETE_TEACHER, GET_TEACHER,
  GET_TEACHERS,
} from '@/graphql/teacher';
import { DEFAULT_PAGE_SIZE } from '@/utils/constance';
import { TBaseTeacher, TTeachersQuery, TTeacherQuery } from '@/utils/types';
import { useMutation, useQuery } from '@apollo/client';
import { message } from 'antd';

// 查询
export const useTeachers = (pageNum = 1, pageSize = DEFAULT_PAGE_SIZE) => {
  const { data, loading, refetch } = useQuery<TTeachersQuery>(GET_TEACHERS, {
    variables: {
      page: {
        pageNum,
        pageSize,
      },
    },
  });
  return {
    data: data?.getTeachers.data,
    page: data?.getTeachers.page || {
      pageNum: 1,
      pageSize: DEFAULT_PAGE_SIZE,
      total: 0,
    },
    loading,
    refetch,
  };
};

// 详情
export const useTeacherInfo = (id?:string) => {
  const { data, loading } = useQuery<TTeacherQuery>(GET_TEACHER, {
    skip: !id,
    variables: {
      id,
    },
  });
  return { data: data?.getTeacherInfo.data, loading };
};

// 删除
export const useDeleteTeacher = ():[delHandler:Function, loading:boolean] => {
  const [del, { loading }] = useMutation(DELETE_TEACHER);
  const delHandler = async (id:string, callback:() => void) => {
    const res = await del({
      variables: {
        id,
      },
    });
    if (res.data.deleteTeacher.code === 200) {
      callback();
      message.success(res.data.deleteTeacher.message);
      return;
    }
    message.error(res.data.deleteTeacher.message);
  };
  return [delHandler, loading];
};

// 更新
export const useEditTeacherInfo = (): [editHandler: Function, loading: boolean] => {
  const [edit, { loading }] = useMutation(COMMIT_TEACHER);
  const editHandler = async (
    id:number,
    params:TBaseTeacher,
    callback:()=> void,
  ) => {
    const res = await edit({
      variables: {
        id,
        params,
      },
    });
    if (res.data.commitTeacherInfo.code === 200) {
      message.success(res.data.commitTeacherInfo.message);
      callback();
      return;
    }
    message.error(res.data.commitTeacherInfo.message);
  };
  return [editHandler, loading];
};
